package cn.edu.zafu.bigdata.yh;
import java.io.*;
import java.net.*;

public class UdpTimeClient {
    public static void main(String[] args) {
        String serverAddress = "localhost"; // 服务器的IP地址或主机名
        int port = 6666; // 服务器的端口号
        try {
            // 创建一个DatagramSocket
            DatagramSocket clientSocket = new DatagramSocket();
            System.out.println("UDP Time Client is running");

            // 创建一个字节数组用于发送请求
            byte[] sendData = "Time Request".getBytes();
            // 创建一个DatagramPacket用于发送请求
            InetAddress IPAddress = InetAddress.getByName(serverAddress);
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port);
            // 发送请求到服务器
            clientSocket.send(sendPacket);

            // 创建一个字节数组用于接收数据
            byte[] receiveData = new byte[1024];
            // 创建一个DatagramPacket用于接收服务器响应
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            // 接收服务器响应
            clientSocket.receive(receivePacket);

            // 将响应转换为字符串
            String received = new String(receivePacket.getData(), 0, receivePacket.getLength());
            System.out.println("Time Response from Server: " + received);

            // 关闭客户端Socket
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
